<template>
  <lb-layout
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    class="home"
  >
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="能耗终端:" prop="monitoringNetworkId">
        <remote-select
          v-model="queryParams.monitoringNetworkId"
          varient="networks"
          size="small"
          placeholder="请选择能耗终端"
          clearable
          @input="repaleceCode"
        ></remote-select>
      </el-form-item>
      <el-form-item label="智能设备:" prop="deviceCode">
        <el-select
          v-model="queryParams.deviceCode"
          clearable
          size="small"
          placeholder="请选择智能设备"
          :disabled="!queryParams.monitoringNetworkId"
          @change="getList"
        >
          <el-option
            v-for="item in equipmentOptions"
            :key="item.code"
            :label="item.code"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-hasPermi="['device:load:add']"
          type="primary"
          size="small"
          :disabled="
            !queryParams.monitoringNetworkId && !queryParams.deviceCode
          "
          @click="submit"
          >设置</el-button
        >
        <el-button
          v-hasPermi="['device:read:add']"
          size="small"
          :disabled="
            !queryParams.monitoringNetworkId && !queryParams.deviceCode
          "
          @click="hanldReading"
          >读取</el-button
        >
      </el-form-item>
    </el-form>

    <Title name="24节气时区表" :line="false">
      <el-table :data="model.timeZone">
        <el-table-column prop="name" label="节气" width="150">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.name"
              size="small"
              placeholder="请选择节气"
              @change="(val) => getTime(val, scope.row)"
            >
              <el-option
                v-for="item in season[scope.row.options]"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="timePeriodTableCode" label="时段表" width="150">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.timePeriodTableCode"
              size="small"
              placeholder="请选择时段表"
            >
              <el-option label="时段表1" :value="1"></el-option>
              <el-option label="时段表2" :value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="月" width="150">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.month"
              :min="1"
              :max="12"
              disabled
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="day" label="日" width="150">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.day"
              :min="1"
              :max="31"
              disabled
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </Title>
    <Title name="时段表设置" class="mt10" :line="false">
      <el-form
        ref="form"
        :inline="true"
        :model="model"
        label-width="70px"
        class="form"
      >
        <el-form-item label="时段表1">
          <el-table :data="model.timePeriod1">
            <el-table-column type="index" label="#" width="40">
            </el-table-column>
            <el-table-column prop="feeType" label="费率" width="105">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.feeType"
                  size="small"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="时" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.hour"
                  :min="0"
                  :max="24"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="分" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.minute"
                  :min="0"
                  :max="60"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="时段表2">
          <el-table :data="model.timePeriod2">
            <el-table-column type="index" label="#" width="40">
            </el-table-column>
            <el-table-column prop="feeType" label="费率" width="105">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.feeType"
                  size="small"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="时" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.hour"
                  :min="0"
                  :max="24"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="分" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.minute"
                  :min="0"
                  :max="60"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </Title>
  </lb-layout>
</template>

<script>
import { mapState } from "vuex";
import { list, reading, timeInsert, getEquipments } from "@/api/iot/loadTariff";
import RemoteSelect from "@/components/Select/RemoteSelect";
export default {
  name: "dayparting",
  dicts: ["sys_job_group", "sys_job_status"],
  components: { RemoteSelect },
  data() {
    return {
      equipmentOptions: [],
      // 遮罩层
      loading: false,
      options: [
        {
          value: 1,
          label: "尖峰",
        },
        {
          value: 2,
          label: "高峰",
        },
        {
          value: 3,
          label: "平常",
        },
        {
          value: 4,
          label: "低谷",
        },
      ],
      season: {
        spring: [
          {
            value: "立春",
            label: "立春",
          },
          {
            value: "雨水",
            label: "雨水",
          },
          {
            value: "惊蛰",
            label: "惊蛰",
          },
          {
            value: "春分",
            label: "春分",
          },
          {
            value: "清明",
            label: "清明",
          },
          {
            value: "谷雨",
            label: "谷雨",
          },
        ],
        summer: [
          {
            value: "立夏",
            label: "立夏",
          },
          {
            value: "小满",
            label: "小满",
          },
          {
            value: "芒种",
            label: "芒种",
          },
          {
            value: "夏至",
            label: "夏至",
          },
          {
            value: "小暑",
            label: "小暑",
          },
          {
            value: "大暑",
            label: "大暑",
          },
        ],
        autumn: [
          {
            value: "立秋",
            label: "立秋",
          },
          {
            value: "处暑",
            label: "处暑",
          },
          {
            value: "白露",
            label: "白露",
          },
          {
            value: "秋分",
            label: "秋分",
          },
          {
            value: "寒露",
            label: "寒露",
          },
          {
            value: "霜降",
            label: "霜降",
          },
        ],
        winter: [
          {
            value: "立冬",
            label: "立冬",
          },
          {
            value: "小雪",
            label: "小雪",
          },
          {
            value: "大雪",
            label: "大雪",
          },
          {
            value: "冬至",
            label: "冬至",
          },
          {
            value: "小寒",
            label: "小寒",
          },
          {
            value: "大寒",
            label: "大寒",
          },
        ],
      },
      // 查询参数
      queryParams: {
        monitoringNetworkId: "",
        deviceCode: "",
      },
      model: {
        timePeriod1: [],
        timePeriod2: [],
        timeZone: [],
        solarTermsList: [], //节气表
      },
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.id,
    }),
  },
  mounted() {
    this.getList();
  },
  methods: {
    getTime(val, item) {
      const data = this.model.solarTermsList.find((_) => _.name === val);
      item.month = data.month;
      item.day = data.day;
    },
    repaleceCode() {
      this.queryParams.deviceCode = "";
      this.resetList();
      this.getEquipmentList();
    },
    getEquipmentList() {
      getEquipments({
        monitoringNetworkId: this.queryParams.monitoringNetworkId,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.equipmentOptions = res.rows;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300045");
        });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      list(this.queryParams)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (!this.queryParams.deviceCode) {
            this.resetList();
            this.resetTimeList(res.data.solarTermsList);
            return false;
          }
          this.model = res.data;
          this.model.timePeriod1 = this.model.timePeriod1.map((item) => {
            item.feeType = item.feeType === 0 ? "" : item.feeType;
            return item;
          });
          this.model.timePeriod2 = this.model.timePeriod2.map((item) => {
            item.feeType = item.feeType === 0 ? "" : item.feeType;
            return item;
          });
          this.model.timeZone = this.model.timeZone.map((item, index) => {
            const arr = ["spring", "summer", "autumn", "winter"];
            item.options = arr[index];
            item.timePeriodTableCode =
              item.timePeriodTableCode === 0 ? "" : item.timePeriodTableCode;
            return item;
          });
        })
        .catch((err) => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!300041");
        });
    },
    resetList() {
      this.model.deviceCode = "";
      this.model.timePeriod1 = [];
      this.model.timePeriod2 = [];
      for (let i = 0; i < 14; i++) {
        this.model.timePeriod1.push({
          feeType: "",
          hour: 0,
          minute: 0,
        });
        this.model.timePeriod2.push({
          feeType: "",
          hour: 0,
          minute: 0,
        });
      }
    },
    resetTimeList(data) {
      const list = data.filter(
        (item) =>
          item.name === "立春" ||
          item.name === "立夏" ||
          item.name === "立秋" ||
          item.name === "立冬"
      );
      this.model.timeZone = list.map((item, index) => {
        const arr = ["spring", "summer", "autumn", "winter"];
        item.options = arr[index];
        item.timePeriodTableCode = "";
        return item;
      });
    },
    // 人工读取
    hanldReading() {
      this.loading = true;
      const data = {
        sysUserId: this.userId,
        ...this.model,
        ...this.queryParams,
      };
      reading(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success(res.msg);
        })
        .catch((err) => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!300042");
        });
    },

    /** 设置按钮 */
    submit() {
      const list = this.model.timePeriod1.filter((item) => item.feeType);
      if (list.length <= 0) {
        this.$message.warning("时段表1设置费率有误");
        return false;
      }
      const list2 = this.model.timePeriod2.filter((item) => item.feeType);
      if (list2.length <= 0) {
        this.$message.warning("时段表2设置费率有误");
        return false;
      }
      const flag = this.checkArrayObjectValueRepeat(this.model.timePeriod1);
      const flag2 = this.checkArrayObjectValueRepeat(this.model.timePeriod2);
      if (flag) {
        this.$message.warning("时段表1设置时分有误");
        return false;
      }
      if (flag2) {
        this.$message.warning("时段表2设置时分有误");
        return false;
      }
      const data = {
        sysUserId: this.userId,
        ...this.queryParams,
        ...this.model,
      };
      this.loading = true;
      timeInsert(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success(res.msg);
        })
        .catch((err) => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!300044");
        });
    },
    handlerClick(key) {
      if (this[key].data.length > 13) {
        this.$message.warning("不能添加更多了");
        return false;
      }
      this[key].data.push({ value: undefined });
    },
    checkArrayObjectValueRepeat(dataArr) {
      let arr = [];
      let flag = false;
      dataArr.some((item) => {
        if (
          (!item.hour && item.hour !== 0) ||
          (!item.minute && item.minute !== 0)
        ) {
          flag = true;
          return flag;
        }
        item.str = item.hour.toString() + "-" + item.minute.toString();
        if (item.feeType) {
          if (arr.includes(item.str)) flag = true;
          arr.push(item.str);
          return flag;
        }
      });
      return flag;
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  padding: 10px 20px;
}
.form {
  display: flex;
  .el-form-item {
    display: flex;
  }
}
</style>
